const auth = require('../middlewares/auth')
const Router = require('koa-router')
const router = new Router()
const { koaBody } = require('koa-body')
const { CosUploadFile, cos } = require('../utils/Cos')
const { CustomError } = require('../utils/customError')
const svgCaptcha = require('svg-captcha')
const {
  calculateGrowthStats,
  getMonthlyArticleCounts,
  getLast30DaysViews,
} = require('../services/tagService')
const dayjs = require('dayjs')
const redis = require('../config/redis')
const Setting = require('../models/Setting')

router.prefix('/comm')
// 文件上传
router.post(
  '/uploadImg',
  auth,
  koaBody({
    multipart: true,
    formidable: {
      maxFileSize: 10 * 1024 * 1024, // 限制10MB
    },
  }),
  async (ctx) => {
    const uploadType = process.env.USE_COS
    const type = ctx.query.type
    if (uploadType) {
      // 腾讯云 COS 上传
      const file = ctx.request.files.file
      const u = await CosUploadFile(file, type)
      if (u.code === 200) {
        ctx.body = u
      } else {
        return (ctx.body = {
          code: u.code,
          message: u.message,
        })
      }
    } else {
      // 本地上传
    }
  },
)
// 获取文件临时URL（后续按需生成）
router.get('/getTempUrl', auth, async (ctx) => {
  const { key } = ctx.query
  const url = cos.getObjectUrl({
    Bucket: process.env.COS_BUCKET,
    Region: process.env.COS_REGION,
    Key: key,
    Expires: 1800, // 30分钟
    Sign: true,
  })
  ctx.body = { url }
})
// 验证码接口
router.get('/captcha', async (ctx) => {
  if (ctx.path === '/api/comm/captcha') {
    const captcha = svgCaptcha.create()

    // 存储到Cookie（明文）
    // ctx.cookies.set('captcha', captcha.text, {
    //    maxAge: 300000, // 5分钟有效
    //    httpOnly: true  // 防止XSS读取
    // });
    // 存储到Redis
    await redis
      .multi()
      .set(`captcha:${captcha.text.toLowerCase()}`, captcha.text, 'PX', 300000)
      .exec()
    ctx.set('Content-Type', 'image/svg+xml')
    ctx.body = {
      code: 200,
      data: captcha.data,
    }
  }
})
// 验证
router.post('/captchaCheck', async (ctx) => {
  const { captcha } = ctx.request.body
  const cookieCaptcha = ctx.cookies.get('captcha')
  console.log('captcha', cookieCaptcha)
  if (captcha && cookieCaptcha && captcha.toLowerCase() === cookieCaptcha.toLowerCase()) {
    ctx.body = {
      code: 200,
      data: true,
      message: '验证通过',
    }
  } else {
    ctx.body = {
      code: 400,
      data: false,
    }
  }
})

// 使用缓存中间件
const statsCache = new Map()
// 获取文章，分类，标签，访问量
router.get('/getStatistics', auth, async (ctx) => {
  const cacheKey = `stats_${dayjs().format('YYYY-MM')}`
  if (!statsCache.has(cacheKey)) {
    const data = await calculateGrowthStats()
    statsCache.set(cacheKey, data)
    setTimeout(() => statsCache.delete(cacheKey), 300000) // 5分钟缓存
  }
  ctx.body = {
    code: 200,
    data: statsCache.get(cacheKey),
    message: '获取统计信息成功',
  }
})
// 获取指定天数的文章发布量
router.get('/getMonthlyArticleCounts/:day', auth, async (ctx) => {
  if (!ctx.params.day) {
    throw new CustomError(400, '参数错误')
  }
  const day = ctx.params.day
  const result = await getMonthlyArticleCounts(day)
  ctx.body = {
    code: 200,
    data: result,
  }
})
// 获取近7/30/60天访问趋势
router.get('/getLast30DaysViews/:day', auth, async (ctx) => {
  if (!ctx.params.day) {
    throw new CustomError(400, '参数错误')
  }
  const day = ctx.params.day
  const result = await getLast30DaysViews(day)
  ctx.body = {
    code: 200,
    data: result,
  }
})
// 保存系统信息
router.post('/saveSystemInfo', auth, async (ctx) => {
  const systemInfo = ctx.request.body
  if (!systemInfo) {
    throw new CustomError(400, '参数错误')
  }
  try {
    await Setting.update(systemInfo, {
      where: {
        id: 1,
      },
    })
    ctx.body = {
      code: 200,
      data: true,
    }
  } catch (e) {
    return (ctx.body = {
      code: 500,
      data: e.message,
    })
  }
})
module.exports = router
